<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/27
 * Time: 9:12
 */

namespace app\api\controller\finance;
use app\api\controller\common\ApiBase;
use think\Controller;
use Think\Db;
//已收
class Financereceivable extends ApiBase
{
    protected $admin;
    protected $model;
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('Finance');
    }

    /**
     * 添加财务
     */
    public function index(){
        if (request()->isPost()) {
            $post = input('post.');
            $page = isset($post['page']) && $post['page'] != '' ? $post['page'] : 10;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 1;
            $exhibition_id = isset($post['exhibition_id']) && $post['exhibition_id'] != '' ? $post['exhibition_id'] : null;
            $company = isset($post['company']) && $post['company'] != '' ? $post['company'] : null;
            if(empty($exhibition_id)){
                return json(['code'=>0,'msg'=>'展会数据有误']);
            }
            $tabName=$this->getTabName($exhibition_id);
            $param=" and h.id_zhui=".$exhibition_id." and h.is_delete=0 AND h.s_status=1 AND c.status=6";
            if($company){
                $param.=" and h.id_zs in (select id from crm_".$tabName." where company_name like '%$company%' )";
            }
            $sql=" SELECT h.*,c.company_name,c.status as company_status,f.f_total FROM crm_contract as h ";
            $sql.=" LEFT JOIN (SELECT SUM(fee) as f_total,contract_id FROM crm_finance WHERE is_delete=0 GROUP BY contract_id) AS f ON f.contract_id=h.id ";
            $sql.=" LEFT JOIN crm_".$tabName." as c ON c.id=h.id_zs";
            $sql.=" where 1=1 $param";
            $total1=Db::query($sql);
            $sql.=" limit ".($page-1)*$pageSize.",$pageSize";
            $list=Db::query($sql);
            foreach ($list as &$val){
                $val['finance_list']=db('finance')->where(['contract_id'=>$val['id'],'is_delete'=>0])->select();
            }
            $total=count($total1); //st
            return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);
        }else{
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }


    public function getTabName($exhibition_id){
        $result=db('exhibition')->where(['id'=>$exhibition_id])->find();
        $tabName="";
        if($result){
            $tabName=$result['create_tablename'];
        }else{
            return json(['code'=>0,'msg'=>'缺少关键字段','data'=>'']);
        }
        return $tabName;
    }
}